package com.cls.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cls.business.entity.ClassDistributionRecord;
import com.cls.business.mapper.ClassDistributionRecordMapper;
import com.cls.business.service.IClassDistributionRecordService;
import com.cls.common.entity.QueryRequest;
import com.cls.common.enums.EmailTextEnum;
import com.cls.common.utils.EmailSenderUtil;
import com.cls.common.utils.StringUtils;
import com.cls.system.entity.Expert;
import com.cls.system.service.IExpertService;
import com.cls.system.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 课题评审记录表 Service实现
 *
 * @author slx
 * @date 2021-03-02 15:54:14
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ClassDistributionRecordServiceImpl extends ServiceImpl<ClassDistributionRecordMapper, ClassDistributionRecord> implements IClassDistributionRecordService {

    private final ClassDistributionRecordMapper recordMapper;
    private final IExpertService expertService;
    private final IUserService userService;
    private final EmailSenderUtil emailUtil;


    @Override
    public PageInfo<ClassDistributionRecord> findClassDistributionRecords(QueryRequest request, ClassDistributionRecord classDistributionRecord) {
        LambdaQueryWrapper<ClassDistributionRecord> queryWrapper = new LambdaQueryWrapper<>();
        // TODO 设置查询条件
        queryWrapper.eq(ClassDistributionRecord::getPlanId, classDistributionRecord.getPlanId());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ClassDistributionRecord> list = this.list(queryWrapper);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public PageInfo<ClassDistributionRecord> findClassDistributionRecordsByPlanId(QueryRequest request, ClassDistributionRecord classDistributionRecord) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ClassDistributionRecord> list = recordMapper.findRecordsByPlanId(classDistributionRecord.getPlanId());

        PageInfo<ClassDistributionRecord> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createClassDistributionRecord(ClassDistributionRecord classDistributionRecord) {
        this.save(classDistributionRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateClassDistributionRecord(ClassDistributionRecord classDistributionRecord) {
        this.saveOrUpdate(classDistributionRecord);
    }


    /**
     * 删除
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteClassDistributionRecords(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.removeByIds(list);
    }

    @Override
    public PageInfo<Expert> findClassDistributionRecordsByExpertId(QueryRequest request, Expert expert, Long planId) {
        List<Long> ids = recordMapper.findExpertIdsByExcludPlanId(planId);

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        LambdaQueryWrapper<Expert> wrapper = new LambdaQueryWrapper<>();
        if (!ids.isEmpty()) {
            wrapper.notIn(Expert::getExpertId, ids);
        }
        if (StringUtils.isNotBlank(expert.getName())) {
            wrapper.like(Expert::getName, expert.getName());
        }
        if (StringUtils.isNotBlank(expert.getSubjectTypeCode())) {
            wrapper.eq(Expert::getSubjectTypeCode, expert.getSubjectTypeCode());
        }
        if (Objects.nonNull(expert.getIsMember())) {
            wrapper.eq(Expert::getIsMember, expert.getIsMember());
        }
        wrapper.eq(Expert::getIsPublish, true);
        List<Expert> list = expertService.list(wrapper);
        PageInfo<Expert> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    public PageInfo<ClassDistributionRecord> findRecordsAndYearByExpertId(QueryRequest request, ClassDistributionRecord classDistributionRecord) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ClassDistributionRecord> list = recordMapper.findRecordsAndYearByExpertId(classDistributionRecord.getExpertId());
        PageInfo<ClassDistributionRecord> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBatchAndCreatUser(List<Expert> experts, Long planId, String year) {
        List<ClassDistributionRecord> recordList = new ArrayList<>();
        for (Expert expert : experts) {
            ClassDistributionRecord record = new ClassDistributionRecord();
            record.setDistributionDate(new Date());
            record.setExpertId(expert.getExpertId());
            record.setPlanId(planId);
            record.setReviewFinished(false);
            recordList.add(record);
            String mobile = expert.getMobile();
            String password = "123456";
            if (mobile != null && mobile.length() > 10) {
                password = mobile.substring(3, 9);
            }
            //         发送邮件
            String format = String.format(EmailTextEnum.CLASS_PROMPT_TEXT.getText(), year, expert.getMobile(), password);
            emailUtil.sendEmail(EmailTextEnum.CLASS_PROMPT.getText(), format, expert.getEmail());

        }
        recordList.forEach(item->{
            save(item);
        });
//        创建用户
        userService.createExpertUsers(experts, null);

    }
}
